<?php

class ConfigService extends \BaseService{

    /**
     * @param [string]  dbUsername  数据库连接用户名
     * @param [string]  dbPassword  数据库连接密码
     * @return [array] [异常信息]
     */
    public static function getConnection($data){

        //创建数据库连接
        try {
            $conn = new PDO("mysql:host=".$data['servername'].";dbname=mysql", $data['dbUsername'], $data['dbPassword']);
            return $conn;
        }catch(PDOException $e){
            throw new ConnectException;
        }
    }

    /**
     * @param [string]  dbName      配置数据库名
     * @param [string]  prefix      表名前缀
     * @return [array] [异常信息]
     */
    public static function createDataBase($data, $conn){

        //创建数据库
        try {
            // 设置 PDO 错误模式为异常
            $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "CREATE DATABASE ".$data['dbName'];
            // 使用 exec() ，因为没有结果返回
            $conn->exec($sql);
            $content = <<<Eof
<?php

return [
        'host'      => '{$data['servername']}',

        'database'  => '{$data['dbName']}',

        'username'  => '{$data['dbUsername']}',

        'password'  => '{$data['dbPassword']}',
        
        'prefix'    => '{$data['prefix']}',
        ];
Eof;
            File::put(app_path().'/config/dbConfig.php', $content);
            
        }catch(PDOException $e){
            throw new DatabaseExistsException;
        }
        return self::getResult("Database ".$data['dbName']." created successfully<br>");
    }

    /**
     * @param 配置数据库名       dbName
     * @param 表名前缀           prefix
     * @return [array] [异常信息]
     */
    // public static function dropDataBase($data, $conn){

    //     //创建数据库
    //     try {
    //         // 设置 PDO 错误模式为异常
    //         $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    //         $sql = "DROP DATABASE ".$data['dbName'];
    //         // 使用 exec() ，因为没有结果返回
    //         $conn->exec($sql);
    //     }catch(ParameterInvalidException $e){
    //         throw $e;
    //     }catch(Exception $e){
    //         dd($e);
    //         throw new LinkException;
    //     }
    //     return self::getResult("Database ".$data['dbName']." droped successfully<br>");
    // }

    /**
     * 迁移数据库所需要的表
     * @return [type] [description]
     */
    public static function migration(){
        try{
            //迁移sentry表格
            Schema::create('users', function($table){
                $table->increments('id');
                $table->string('username');
                $table->string('password');
                $table->text('permissions')->nullable();
                $table->boolean('activated')->default(0);
                $table->string('activation_code')->nullable();
                $table->timestamp('activated_at')->nullable();
                $table->timestamp('last_login')->nullable();
                $table->string('persist_code')->nullable();
                $table->string('reset_password_code')->nullable();
                $table->string('first_name')->nullable();
                $table->string('last_name')->nullable();
                $table->timestamps();

                // We'll need to ensure that MySQL uses the InnoDB engine to
                // support the indexes, other engines aren't affected.
                $table->engine = 'InnoDB';
                $table->unique('username');
                $table->index('activation_code');
                $table->index('reset_password_code');
            });

            Schema::create('groups', function($table){
                $table->increments('id');
                $table->string('name');
                $table->text('permissions')->nullable();
                $table->timestamps();

                // We'll need to ensure that MySQL uses the InnoDB engine to
                // support the indexes, other engines aren't affected.
                $table->engine = 'InnoDB';
                $table->unique('name');
            });

            Schema::create('users_groups', function($table){
                $table->integer('user_id')->unsigned();
                $table->integer('group_id')->unsigned();

                // We'll need to ensure that MySQL uses the InnoDB engine to
                // support the indexes, other engines aren't affected.
                $table->engine = 'InnoDB';
                $table->primary(array('user_id', 'group_id'));
            });

            Schema::create('throttle', function($table){
                $table->increments('id');
                $table->integer('user_id')->unsigned()->nullable();
                $table->string('ip_address')->nullable();
                $table->integer('attempts')->default(0);
                $table->boolean('suspended')->default(0);
                $table->boolean('banned')->default(0);
                $table->timestamp('last_attempt_at')->nullable();
                $table->timestamp('suspended_at')->nullable();
                $table->timestamp('banned_at')->nullable();

                // We'll need to ensure that MySQL uses the InnoDB engine to
                // support the indexes, other engines aren't affected.
                $table->engine = 'InnoDB';
                $table->index('user_id');
            });

            Schema::create('model', function($table){
                $table->increments('id');
                $table->string('name');
                $table->string('table_name');
                $table->timestamps();
            });

            Schema::create('field', function($table){
                $table->increments('id');
                $table->string('name');
                $table->string('type');
                $table->string('display_name');
                $table->integer('model_id')->unsigned();
                $table->foreign('model_id')->references('id')->on('model')->onDelete('cascade');
                $table->timestamps();
            });

            Schema::create('category', function($table){
                $table->increments('id');
                $table->string('name');
                $table->integer('model_id')->unsigned();
                $table->foreign('model_id')->references('id')->on('model')->onDelete('cascade');
                $table->timestamps();
            });

            //增加字段类型表
            Schema::create('type',function($table){
                $table->increments('id');
                $table->string('type_name');
                $table->timestamps();
            });

            //增加字段类型
            Type::create(array('type_name' => 'string'));
            Type::create(array('type_name' => 'integer'));
            Type::create(array('type_name' => 'boolean'));
            Type::create(array('type_name' => 'date'));
            Type::create(array('type_name' => 'dateTime'));
            Type::create(array('type_name' => 'double'));
            Type::create(array('type_name' => 'text'));
            Type::create(array('type_name' => 'time'));
            Type::create(array('type_name' => 'timestamp'));
            Type::create(array('type_name' => 'longText'));
            Type::create(array('type_name' => 'decimal'));
        }catch(Exception $e){
            //出问题的情况
            if(Schema::hasTable('users')){
                Schema::drop('users');
            }
        }
    }
}